$(document).ready(function() {
    $(".protClass").each(function(i,v){
        v.val( $("#" + v.id + "Selected").val() );
    });
    $(".errorLabel").each(function(i,v){
        $(value).hide();
    });
});

function validate(){
    jQuery.validator.addMethod("isUniqueDrug", function(value, element){
        var parentTable = $("#table_drugs");
        var timeRepeated = 0;
        $(parentTable.find('select')).each(function () {
            if ($(this).val() == value) {
                timeRepeated++;
            }
        });
        if (timeRepeated == 1 || timeRepeated == 0) {
            return true
        }
        else {
            return false
        }
    });


    jQuery.validator.addMethod("isUniqueProt", function(value, element){
        var parentTable = $("#table_prots");
        var timeRepeated = 0;
        $(parentTable.find('select')).each(function () {
            if ($(this).val() == value) {
                timeRepeated++;
            }
        });
        if (timeRepeated == 1 || timeRepeated == 0) {
            return true
        }
        else {
            return false
        }
    });

    $("#formEdit")
        .validate(
        {
            rules : {
                'importacion.compromisopais.id': "required",
                'importacion.importPermit' : "required"
            }
        })


    $(".drogaSelect").each(function(index,value){
        var thisId = value.id;
        $("#" + thisId).rules("add", {
            required:true,
            isUniqueDrug:true,
            messages : {
                isUniqueDrug: "Repeated"
            }
        });
    });

    $(".protSelect").each(function(index,value){
        var thisId = value.id;
        $("#" + thisId).rules("add", {
            required:true,
            isUniqueProt:true,
            messages : {
                isUniqueProt: "Repeated"
            }
        });
    });

    $(".qtyClass").each(function(index,value){
        var thisId = value.id;
        $("#" + thisId).rules("add", {
            required:true,
            number: true
        });
    });

    $(".unitClass").each(function(index,value){
        var thisId = value.id;
        $("#" + thisId).rules("add", {
            required:true
        });
    });

    if( $("#formEdit").valid() ){
        var ok = true;
        $(".qtyClass").each(function(index,value){
            var takeoffs = 0;
            $(value.id + "takeOff").each(function(i,v){
                takeoffs = parseInt(takeoffs,10) + parseInt(v.value,10);
            });
            if( parseInt(value.value,10) < parseInt(takeoffs,10) ){
                $("#" + value.id + "Error").show();
                ok = false;
            }
            else{
                $("#" + value.id + "Error").hide();
            }
        });
        return ok;
    }
    else{
        return false;
    }
}

function validateDiscount(){
    $.validator.addMethod("lessThanBalance", function(value, element, arg){
        return parseInt(value,10) <= parseInt($("#balance").val(),10);
    });

    $("#formEdit")
        .validate(
        {
            rules : {
                'protocolToDiscountId': "required",
                'takeOff' : {
                    required : true,
                    number : true,
                    lessThanBalance: true
                }
            },
            messages : {
                'takeOff' : {
                    lessThanBalance: "Invalid discount"
                }
            }
        })

}

function deleteDrug(tableId, fila){
    var table = document.getElementById(tableId);
    var cant = document.getElementById("cantDrugs");

    var rows = table.getElementsByTagName('tr');
    var size = rows.length;
    for(var j = 0; j < rows.length; j++ ){
        if(rows[j].id == fila[0].id && rows[j].cells[1].id == fila[0].cells[1].id){
            break;
        }
    }

    if(cant.value == 1){
        var borrados = 0;
        var x = j - 1;
        while(borrados < 3){
            if(rows[x].cells[1] != null){
                rows[x].cells[1].children[0].value="";
                borrados++;
            }
            x--;
        }
        return;
    }

    var borrados = 0;
    var x = j;
    while(borrados < 4){
        rows[x].parentNode.removeChild(rows[x]);
        if(rows[x].cells[1] != null){
            borrados++;
        }
        x--;
    }

    var val = parseInt(cant.value,10) - parseInt(1,10);
    cant.value = val;
}

function deleteProt(tableId, fila){
    var table = document.getElementById(tableId);
    var cant = document.getElementById("cantProts");

    var rows = table.getElementsByTagName('tr');
    var size = rows.length;
    for(var j = 0; j < rows.length; j++ ){
        if(rows[j].id == fila[0].id && rows[j].cells[0].id == fila[0].cells[0].id){
            break;
        }
    }

    if(cant.value == 1){
        var borrados = 0;
        var x = j - 1;
        while(borrados < 1){
            if(rows[x].cells[1] != null){
                rows[x].cells[1].children[0].value="";
                borrados++;
            }
            x--;
        }
        return;
    }

    var borrados = 0;
    var x = j;
    while(borrados < 2){
        rows[x].parentNode.removeChild(rows[x]);
        if(rows[x].cells[1] != null){
            borrados++;
        }
        x--;
    }

    var val = parseInt(cant.value,10) - parseInt(1,10);
    cant.value = val;
}

function addDrug(tableID){
    var table = document.getElementById(tableID);
    var rowCount = table.rows.length;

    var cant = document.getElementById("cantDrugs");
    var val = parseInt(cant.value,10) + parseInt(1,10);
    cant.value = val;

    var ultimoId = document.getElementById("ultimoIdDrugs");

    for(var k = ultimoId.value; k>0; k--){
        if (document.getElementById("delDrugCell" + k) != null)
            break;
    }

    var newId = parseInt(ultimoId.value,10) + parseInt(1,10);
    ultimoId.value = newId;

    var idAfter = '#delDrugCell' + k;

    var row5 = $('#delDrugCell' + k).parent().clone()[0];
    row5.cells[1].id="delDrugCell"+newId;
    row5.cssClass="trNuevoDocumento";
    $(row5).css("display", "table-row");
    $(idAfter).parent().after(row5);

    var row4 = $('#unit' + k).parent().parent().clone()[0];
    row4.cells[1].children[0].name="importacion.drogaImportaciones[" + newId + "].unit";
    row4.cells[1].children[0].value="";
    row4.cells[1].children[0].id="unit" + newId;
    row4.cells[1].children[0].cssClass="unitClass";
    $(row4).removeClass("trEspacioAbajo");
    if(row4.cells[1].children.length == 2)
        row4.cells[1].children[1].parentNode.removeChild(row4.cells[1].children[1]);
    $(idAfter).parent().after(row4);

    var row3 = $('#qty' + k).parent().parent().clone()[0];
    row3.cells[1].children[0].name="quantities[" + newId + "]";
    row3.cells[1].children[0].id="qty" + newId;
    row3.cells[1].children[0].value="";
    row3.cells[1].children[0].cssClass="qtyClass";
    if(row3.cells[1].children.length == 2)
        $(row3.cells[1].children[1]).hide();
    $(idAfter).parent().after(row3);

    var row2 = $('#droga' + k).parent().parent().clone()[0];
    row2.cells[1].children[0].name="importacion.drogaImportaciones[" + newId + "].droga.id";
    row2.cells[1].children[0].id="droga" + newId;
    row2.cells[1].children[0].value="";
    row2.cells[1].children[0].cssClass="drogaSelect";
    $(row2.cells[1].children[0]).removeAttr("disabled");
    if(row2.cells[1].children.length == 2){
        row2.cells[1].children[1].name="";
        row2.cells[1].children[1].value="";
    }
    $(idAfter).parent().after(row2);

}

function addProt(tableID){
    var table = document.getElementById(tableID);
    var rowCount = table.rows.length;

    var cant = document.getElementById("cantProts");
    var val = parseInt(cant.value,10) + parseInt(1,10);
    cant.value = val;

    var ultimoId = document.getElementById("ultimoIdProts");

    for(var k = ultimoId.value; k>0; k--){
        if (document.getElementById("delProtCell" + k) != null)
            break;
    }

    var newId = parseInt(ultimoId.value,10) + parseInt(1,10);
    ultimoId.value = newId;

    var idAfter = '#delProtCell' + k;

    var row5 = $('#delProtCell' + k).parent().clone()[0];
    row5.cells[1].id="delProtCell"+newId;
    $(row5).css("display", "table-row");
    row5.cssClass="trNuevoDocumento";
    $(idAfter).parent().after(row5);


    var row4 = $('#protocolo' + k).parent().parent().clone()[0];
    row4.cells[1].children[1].name="protocolo" + newId;
    $(row4.cells[1].children[1]).removeAttr("disabled");
    row4.cells[1].children[1].value="";
    row4.cells[1].children[1].id="protocolo" + newId;
    row4.cells[1].children[1].cssClass="protSelect";
    row4.cells[1].children[0].value="";
    row4.cells[1].children[0].id="protocolo" + newId + "Selected";
    row4.cells[1].children[0].name="importacion.protocoloImportaciones[" + newId + "].protocolo.id";
    $(row4).removeClass("trEspacioAbajo");
    $(idAfter).parent().after(row4);

}

function actualizarProtocolos(url){
        var idsDrogas = "";
        $(".drogaSelect").each(function(i,value){
            if(value.value != ""){
                idsDrogas += value.value;
                idsDrogas += ", ";
            }
        });

        var paisId = $("#country").val();

        $.ajax({
            async:false,
            traditional: true,
            type: "POST",
            url: url,
            data: { "paisId": paisId, "idsDrogas": idsDrogas },
            success: function(result)
            {
                var options = $(result + ' #protocolos')[0].cells[1].children[0].options;
                $(".protSelect").each(function(i,v){
                    var id = v.id;
                    $("#" + id).empty();
                    $("#" + id).html($(options).clone());
                    if( $("#" + id + "Selected") != null){
                        $("#" + id).val($("#" + id + "Selected").val());
                    }
                });
            }
        });
}

function protValue(select){
    $("#" + select.id + "Selected").val(select.value);
}
